package com.model;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;

import com.jweight.*;

public class ProbabilisticDataModel extends StructuredContextDataModel
{
	public ArrayList<JImageComponent> result=new ArrayList<JImageComponent>();
	private HashMap<String, Double> adjestedWeightMap=new HashMap<String, Double>();
	
	
	public ProbabilisticDataModel(String datasource, String url,
			String username, String password, String driverName) {
		super(datasource, url, username, password, driverName);
		// TODO Auto-generated constructor stub
	}

	
	public ResultSet jgetWeightVal(){
		
		ResultSet rSet=null;
		
		String sqlString="select ";
        
        Iterator<String> iter = contextVariables.iterator();
        while (iter.hasNext()) {
              String tempConVar = iter.next();
              if(iter.hasNext())sqlString += tempConVar + ",";
              else sqlString += tempConVar;
            }
        
        sqlString += " from weightvalue where RequestID=(select MAX(RequestID) from weightvalue)";
		try{
			System.out.println(sqlString);
			rSet=fetch(sqlString);				
			
		}catch (Exception e) {
			e.printStackTrace();
			//throw e;
		}
		
	    return rSet;           
	 }
	
	
	@Override
	public int saveUserFeedback(HashMap contextMap, long userID,
			String keyword, String url, long imageId) throws Exception {
		// TODO Auto-generated method stub
		 
		try {
			
			JweightAdjestAlgorithm weightAgestAlgo=new JweightAdjestAlgorithm(this.getContextVariablesList(),getWeightValueMap());
			long imageID=getImageID(url);
			if(imageID!=0){
				adjestedWeightMap=weightAgestAlgo.setWeightVal(""+imageID, this.result);
				saveUsreFeedback(contextMap, imageID, keyword, userID);
			}else{
				System.out.println("user selected google Image");
				saveUserFeedback(contextMap, userID, keyword, url);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}		
		
		return 1;
	}
	private void saveUsreFeedback(HashMap contextMap,long imageID,String keyWord,long userID)throws Exception{
		
		long reqID=getReqCount()+1;
		
		String sql_saveToImage=null;
		String sql_saveToWeightValue_part1="insert into weightvalue (";
		String sql_saveToWeightValue_part2=" values (";
		String sql_saveToHistory_part1=null;
		String sql_saveToHistory_part2=null;
		
		if(userID==Integer.MIN_VALUE){
			sql_saveToHistory_part1="insert into searchhistory (RequestID,Keyword,ImageID,";
	        sql_saveToHistory_part2=" values ('"+reqID+"','"+keyWord+"','"+imageID+"',";
	        
		}else{
			sql_saveToHistory_part1="insert into searchhistory (RequestID,UserID,Keyword,ImageID,";
	        sql_saveToHistory_part2=" values ('"+reqID+"','"+userID+"','"+keyWord+"','"+imageID+"',";	
		}
		String sql_saveToHistory=null;
		String sql_saveToWeightValue=null;              

        Iterator<String> iter = contextVariables.iterator();
        while (iter.hasNext()) {
                
        	String tempConVar = iter.next();
        	if(tempConVar.equals("Keyword"))continue;
        	else if(tempConVar.equals("UserID"))continue;
        	else{
        		if(iter.hasNext()){
        			sql_saveToHistory_part1 += tempConVar + ",";
        			sql_saveToHistory_part2 += "'"+contextMap.get(tempConVar.toLowerCase())+"',";
                
        			sql_saveToWeightValue_part1+= tempConVar+ ",";
        			sql_saveToWeightValue_part2+= "'"+adjestedWeightMap.get(tempConVar)+"',";
                }else{
                	sql_saveToHistory_part1 += tempConVar+")";
                	sql_saveToHistory_part2 +="'"+contextMap.get(tempConVar.toLowerCase())+"')";
               
                	sql_saveToWeightValue_part1+= tempConVar+ ")";
                	sql_saveToWeightValue_part2+= "'"+adjestedWeightMap.get(tempConVar)+"')";
                              
                }  
        	}
        }
        
        sql_saveToHistory = sql_saveToHistory_part1+sql_saveToHistory_part2;
       
        sql_saveToWeightValue=sql_saveToWeightValue_part1+sql_saveToWeightValue_part2;
        System.out.println(sql_saveToWeightValue);
        try {
			//sql_saveToImage="Insert into Image (ImageID,ImageURL) values('"+newImageID+"','"+url+"')";
			//save(sql_saveToImage);
			save(sql_saveToHistory);
			save(sql_saveToWeightValue);
		} catch (Exception e) {

			e.printStackTrace();
			throw e;
		}
	}
	
	private int saveUserFeedback(HashMap contextMap,long userID,String keyword, String url) throws Exception{
		
		long newImageID=getImageCount()+1;
		String sql_saveToImage="Insert into Image (ImageID,ImageURL) values('"+newImageID+"','"+url+"')";
		
		long reqID=getReqCount()+1;
		
				
		String sql_saveToHistory_part1=null;
		String sql_saveToHistory_part2=null;
		
		if(userID==Integer.MIN_VALUE){
			sql_saveToHistory_part1="insert into searchhistory (RequestID,Keyword,ImageID,";
	        sql_saveToHistory_part2=" values ('"+reqID+"','"+keyword+"','"+newImageID+"',";
	        
		}
		else{
			sql_saveToHistory_part1="insert into searchhistory (RequestID,UserID,Keyword,ImageID,";
	        sql_saveToHistory_part2=" values ('"+reqID+"','"+userID+"','"+keyword+"','"+newImageID+"',";
	        	
		}
		String sql_saveToHistory=null;
		String sql_saveToWeightValue=null;              

        Iterator<String> iter = contextVariables.iterator();
        while (iter.hasNext()) {
                
        	String tempConVar = iter.next();
        	if(tempConVar.equals("Keyword"))continue;
        	else if(tempConVar.equals("UserID"))continue;
        	else{
        		if(iter.hasNext()){
                sql_saveToHistory_part1 += tempConVar + ",";
                sql_saveToHistory_part2 += "'"+contextMap.get(tempConVar.toLowerCase())+"',";
                              
                }else
                {
                sql_saveToHistory_part1 += tempConVar+")";
                sql_saveToHistory_part2 +="'"+ contextMap.get(tempConVar.toLowerCase())+"')";
                          
                }  
        	}
        }
        
        sql_saveToHistory = sql_saveToHistory_part1+sql_saveToHistory_part2;       
        
        try {
			save(sql_saveToImage);
			save(sql_saveToHistory);
			
		} catch (Exception e) {

			e.printStackTrace();
			throw e;
		}		
		
		return 1;
	}
	
	public HashMap<String,Double> getWeightValueMap(){
		HashMap<String,Double> weightValMap=new HashMap<String, Double>();
		ResultSet tuples=null;
	
		try {
			tuples=jgetWeightVal();

		} catch (Exception e) {
			System.out.println("Error in geting weight values result");

			// TODO: handle exception
		}
		try {
			while(tuples.next()){
				
				//element=new JImage();
				
				for (int i=0;i<contextVariables.size();i++) {
					String context=contextVariables.get(i);				
					weightValMap.put(context, Double.parseDouble(tuples.getString(context)));
				}							
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("Error in reading weidht values");
		}		
		return weightValMap;
	}
				
}

